<template>
  <el-dialog
    title="线索转换"
    append-to-body
    :visible="visible"
    width="840px"
    :close-on-click-modal="false"
    @close="handleClose()"
  >
    <div v-if="step===1" class="clue-change-body">
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="客户" class="clue-change-form" prop="customerName">
          <el-row class="clue-change-row">
            <div class="row-item">
              <el-radio v-model="isAddCustomer" :label="true">新建</el-radio>
              <div class="item-input-new">
                <span class="is-required">客户名</span>
                <el-input v-model="form.customerName" placeholder="请输入客户名" maxlength="50" />
              </div>
            </div>
            <div class="row-icon">
              <img src="@/assets/images/icon-or.png">
            </div>
            <div class="row-item">
              <el-radio v-model="isAddCustomer" :label="false">选择现有</el-radio>
              <div class="item-input-select">
                <vb-select v-model="form.customerId" placeholder="搜索匹配客户" :disabled="isAddCustomer" :load-data="loadCustomer" @change="handleChangeCustomer" />
                <div class="tips">{{ form.customerId?1: 0 }}个客户匹配</div>
              </div>
            </div>
          </el-row>
        </el-form-item>
        <el-form-item label="联系人" label-width="80px" class="clue-change-form" prop="contactName">
          <el-row class="clue-change-row">
            <div class="row-item">
              <el-radio v-model="isAddContact" :label="true">新建</el-radio>
              <div class="item-input-new">
                <span class="is-required">联系人姓名</span>
                <el-input v-model="form.contactName" placeholder="请输入联系人" maxlength="50" />
              </div>
            </div>
            <div class="row-icon">
              <img src="@/assets/images/icon-or.png">
            </div>
            <div class="row-item">
              <el-radio v-model="isAddContact" :label="false">选择现有</el-radio>
              <div class="item-input-select">
                <vb-select v-model="form.contactId" placeholder="搜索匹配联系人" :disabled="isAddContact" :load-data="loadContact" @change="handleChangeContact" />
                <div class="tips">{{ form.contactId?1:0 }}个联系人匹配</div>
              </div>
            </div>
          </el-row>
        </el-form-item>
        <el-form-item label="商机" label-width="80px" class="clue-change-form" prop="chanceName">
          <el-row class="clue-change-row">
            <div class="row-item">
              <el-radio v-model="isAddChance" :label="true">新建</el-radio>
              <div class="item-input-new">
                <span class="is-required">商机名</span>
                <el-input v-model="form.chanceName" placeholder="请输入商机名" maxlength="50" />
              </div>
            </div>
            <div class="row-icon">
              <img src="@/assets/images/icon-or.png">
            </div>
            <div class="row-item">
              <el-radio v-model="isAddChance" :label="false">选择现有</el-radio>
              <div class="item-input-select">
                <vb-select v-model="form.chanceId" placeholder="搜索匹配商机" :disabled="isAddChance" :load-data="loadChance" @change="handleChangeChance" />
                <div class="tips">{{ form.chanceId?1:0 }}个商机匹配</div>
              </div>
            </div>
          </el-row>

        </el-form-item>
        <el-form-item label="所有人" label-width="80px" prop="owner">
          <VbUserDeptInput v-model="form.user" :display-user-name="true" type="user" placeholder="请选择所有人" @change="handleChangeUser" />
          <!-- <el-input v-model="form.owner" style="width:215px" placeholder="请输入所有人" maxlength="50" /> -->
        </el-form-item>
      </el-form>
      <el-row style="text-align:right">
        <el-button plain @click="handleClose()">取消</el-button>
        <el-button type="primary" @click="handleSubmit">转换</el-button>
      </el-row>
    </div>
    <div v-if="step===2" class="clue-change-body">
      <div class="clue-change-row changed-step2">
        <div class="row-item">
          <div class="row-item-title">
            客户
          </div>
          <div class="row-item-name">
            <img src="@/assets/images/icon-user.png">
            <span class="a-link" @click="gotoDetail('customer',result.customerSwitchDetail.id)">{{ result.customerSwitchDetail.name }}</span>

          </div>
          <div class="row-item-content">
            <span class="title">电话：</span>
            <span class="content" title="">{{ result.customerSwitchDetail.phone }}</span>

          </div>
          <div class="row-item-content">
            <span class="title">邮箱：</span>
            <span class="content" title="">{{ result.customerSwitchDetail.email }}</span>

          </div>
          <div class="row-item-content">
            <span class="title">地址：</span>
            <span class="content" title="">{{ formatAddress( result.customerSwitchDetail) }}</span>

          </div>
          <div class="row-item-content">
            <span class="title">所有人：</span>
            <span class="content" title="">{{ result.customerSwitchDetail.owner }}</span>

          </div>
        </div>
        <div class="row-item">
          <div class="row-item-title">
            联系人
          </div>
          <div class="row-item-name">
            <img src="@/assets/images/icon-user.png">
            <span class="a-link" @click="gotoDetail('contacts',result.contactsSwitchDetail.id)"> {{ result.contactsSwitchDetail.name }}</span>

          </div>
          <div class="row-item-content">
            <span class="title">职务：</span>
            <span class="content" title="">  {{ result.contactsSwitchDetail.position }}</span>

          </div>
          <div class="row-item-content">
            <span class="title">客户：</span>
            <span class="content" title="">  {{ result.contactsSwitchDetail.customerName }}</span>

          </div>
          <div class="row-item-content">
            <span class="title">电话：</span>
            <span class="content" title="">  {{ result.contactsSwitchDetail.phone }}</span>

          </div>
          <div class="row-item-content">
            <span class="title">邮箱：</span>
            <span class="content" title="">  {{ result.contactsSwitchDetail.email }}</span>

          </div>
        </div>

        <div class="row-item">
          <div class="row-item-title">
            商机
          </div>
          <div class="row-item-name">
            <img src="@/assets/images/icon-user.png">
            <span class="a-link" @click="gotoDetail('chance',result.busChanceSwitchDetail.id)">{{ result.busChanceSwitchDetail.name }}</span>
          </div>
          <div class="row-item-content">
            <span class="title">客户名：</span>
            <span class="content" title="">  {{ result.busChanceSwitchDetail.customerName }}</span>

          </div>
          <div class="row-item-content">
            <span class="title">结束日期：</span>
            <span class="content" title="">  {{ formatTime(result.busChanceSwitchDetail.endDate,'YYYY-MM-DD') }}</span>

          </div>
          <div class="row-item-content">
            <span class="title">所有人：</span>
            <span class="content" title="">  {{ result.busChanceSwitchDetail.owner }}</span>
          </div>
        </div>

      </div>
      <el-row style="text-align:right">
        <el-button type="primary" @click="handleClose(true)">返回线索</el-button>
      </el-row>
    </div>
  </el-dialog>

</template>
<script>
import { getCustomerSelect } from '@/api/customer'
import { getContactsSelect } from '@/api/contact'
import { getChanceSelect } from '@/api/chance'
import { switchClue, switchClueDetail } from '@/api/clue'
import { formatTime } from '@/utils/tools'
import VbUserDeptInput from '@/components/VbUsers/VbUserDeptInput'
export default {
  name: 'ClueTransfer',
  components: { VbUserDeptInput },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {
        return {}
      }
    }

  },
  data() {
    const validateCustomer = (rule, value, callback) => {
      if (this.isAddCustomer) {
        if (value === '') {
          callback(new Error('请输入客户名'))
        } else {
          callback()
        }
      } else {
        if (!this.form.customerId) {
          callback(new Error('请搜索匹配客户'))
        } else {
          callback()
        }
      }
    }
    const validateContact = (rule, value, callback) => {
      if (this.isAddContact) {
        if (value === '') {
          callback(new Error('请输入联系人姓名'))
        } else {
          callback()
        }
      } else {
        if (!this.form.contactId) {
          callback(new Error('请搜索匹配联系人'))
        } else {
          callback()
        }
      }
    }
    const validateChance = (rule, value, callback) => {
      if (this.isAddChance) {
        if (value === '') {
          callback(new Error('请输入商机名'))
        } else {
          callback()
        }
      } else {
        if (!this.form.chanceId) {
          callback(new Error('请搜索匹配商机'))
        } else {
          callback()
        }
      }
    }
    return {
      step: 1,
      isAddCustomer: true,
      isAddContact: true,
      isAddChance: true,
      form: {
        customerName: '',
        customerId: '',
        customerSelectName: '',
        contactId: '',
        contactName: '',
        contactSelectName: '',
        chanceId: '',
        chanceName: '',
        chanceSelectName: '',
        owner: '',
        user: {

        }
      },
      result: {
        busChanceSwitchDetail: {},
        contactsSwitchDetail: {},
        customerSwitchDetail: {}

      },
      rules: {
        customerName: [
          { validator: validateCustomer, trigger: 'blur' }
        ],
        contactName: [
          { validator: validateContact, trigger: 'blur' }
        ],
        chanceName: [
          { validator: validateChance, trigger: 'blur' }
        ],
        owner: [
          { required: true, message: '请输入所有人姓名', trigger: 'blur' }
        ]

      }
    }
  },
  created() {
    const data = JSON.parse(JSON.stringify(this.data))
    this.form.customerName = data.companyName
    this.form.contactName = data.name
    this.form.chanceName = data.companyName
    this.form.owner = data.owner
    this.form.user = {
      id: '',
      userName: data.owner
    }
  },
  methods: {
    formatTime,
    loadCustomer(params) {
      return getCustomerSelect(params).then(res => {
        return res
      })
    },
    loadContact(params) {
      return getContactsSelect(params).then(res => {
        return res
      })
    },
    loadChance(params) {
      return getChanceSelect(params).then(res => {
        return res
      })
    },
    handleChangeUser(v) {
      this.form.owner = v.userName
    },
    handleClose(v) {
      console.log('v:', v)
      this.$emit('close', v)
    },
    gotoDetail(path, id) {
      this.$router.push({ path: `/${path}/info`, query: { id }})
    },

    handleSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const list = []

          if (this.isAddCustomer) {
            list.push({
              id: '',
              name: this.form.customerName,
              type: 1
            })
          } else {
            list.push({
              id: this.form.customerId,
              name: this.form.customerSelectName,
              type: 1
            })
          }
          // 联系人
          if (this.isAddContact) {
            list.push({
              id: '',
              name: this.form.contactName,
              type: 2
            })
          } else {
            list.push({
              id: this.form.contactId,
              name: this.form.contactSelectName,
              type: 2
            })
          }
          // 商机
          if (this.isAddChance) {
            list.push({
              id: '',
              name: this.form.chanceName,
              type: 3
            })
          } else {
            list.push({
              id: this.form.chanceId,
              name: this.form.chanceSelectName,
              type: 3

            })
          }
          // 提交数据
          const data = {
            'id': this.data.id,
            'list': list,
            owner: this.form.owner
          }
          this.loading = true
          switchClue(data).then(res => {
            this.$message.success('转换成功')

            switchClueDetail({ id: this.data.id }).then(res => {
              console.log('11111:', res)
              this.result = res
              this.step = 2
              this.loading = false
            }).catch(ex => {
              this.$message.error(ex.message || '获取转换结果失败')
              this.loading = false
            })
          }).catch(ex => {
            this.$message.error(ex.message || '转换失败')
            this.loading = false
          })
        }
      })
    },
    handleChangeChance(v) {
      this.form.chanceSelectName = v.name
      this.form.chanceId = v.id
    },
    handleChangeCustomer(v) {
      this.form.customerSelectName = v.name
      this.form.customerId = v.id
    },
    handleChangeContact(v) {
      this.form.contactSelectName = v.name
      this.form.contactId = v.id
    },
    formatAddress(detail) {
      if (detail && detail.receiveList && detail.receiveList.length > 0) {
        return `${detail.receiveList[0].province}${detail.receiveList[0].city}${detail.receiveList[0].county}${detail.receiveList[0].address}`
      }
      return ''
    }
  }
}
</script>
<style lang="scss">
.clue-change-body{
  .clue-change-form{
    border-bottom: 1px solid #e5e5e5;
    padding-bottom: 20px;
  }
  .el-form{
    width:100%;
  }
  .clue-change-row{
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    &.changed-step2{
      padding-bottom: 20px;
      justify-content: space-between;
      .row-item{
        width: 240px;
        background-color:#f5f6f7;
        border-radius:8px;
        padding:20px;
        height: 221px;
        .row-item-title{
          display: flex;
          align-items: center;
          font-weight:700;
          color:rgba(0, 0, 0, 0.85);
          font-size:16px;

        }
        .row-item-content{

          display: flex;
          align-items: center;
          padding: 5px 0;
          .title{
            width:70px ;
            text-align: left;
            flex-shrink: 0;
            color: #333;
            margin: 0;
            font-weight: 400;

           }
           .content{
            color: #666;
            flex: 1;
             overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
           }
        }
        .row-item-name{
          display: flex;
          align-items: center;
          font-weight:700;
          color:#333333;
          padding: 10px 0;
          img{
            width: 24px;
            height: 24px;
            margin-right: 10px;
          }
          .a-link{
            cursor: pointer;
            &:hover{
              text-decoration: underline;
              color: $--color-primary;
            }
          }
        }
      }
    }
    .row-item{

      padding-left: 20px;
      .item-input-new{
        background-color:#f5f6f7;
        padding: 20px 10px;
        display: flex;
        flex-direction: column;
        .is-required{
          &::before{
              content: "*";
              color: #ff4d4f;
              margin-right: 4px;
          }
        }

        .el-input{
          width:215px
        }
      }
      .item-input-select{
        padding-top: 20px;
        .tips{
          background-color:#ffffff;
          border:1px solid;
          border-color:rgba(0, 0, 0, 0.15);
          border-radius:2px;
          margin-top: 10px;
          padding-left: 20px;
          width: 215px;
        }

      }

    }
    .row-icon{
      width: 60px;
      flex-shrink: 0;
      text-align: center;
      img{
        width:24px;
        height: 24px;
      }
    }

  }

}
</style>
